package servlets;

import beans.ExpenseRecord;
import db.ExpenseRecordDAO;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/CostServlet")
public class CostServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ExpenseRecordDAO expenseRecordDAO;

    @Override
    public void init() throws ServletException {
        try {
            // 初始化数据库连接
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://118.31.103.48:3066/vehicle?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowPublicKeyRetrieval=true";
            String username = "root";
            String password = "123456";
            Connection connection = DriverManager.getConnection(url, username, password);
            expenseRecordDAO = new ExpenseRecordDAO(connection);
        } catch (ClassNotFoundException | SQLException e) {
            throw new ServletException("Error initializing CostServlet", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取查询参数
            String cardID = request.getParameter("plateNumber");
            String status = request.getParameter("status");
            String startDate = request.getParameter("startDate");
            String endDate = request.getParameter("endDate");

            // 查询费用记录
            List<ExpenseRecord> expenseRecords;
            if ((cardID != null && !cardID.isEmpty()) ||
                    (status != null && !status.isEmpty()) ||
                    (startDate != null && !startDate.isEmpty()) ||
                    (endDate != null && !endDate.isEmpty())) {
                expenseRecords = expenseRecordDAO.searchExpenseRecords(cardID, status, startDate, endDate);
            } else {
                expenseRecords = expenseRecordDAO.getAllExpenseRecords();
            }

            // 设置属性并转发到JSP
            request.setAttribute("expenseRecords", expenseRecords);
            request.getRequestDispatcher("Cost.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException("Error retrieving expense records", e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    public void destroy() {
        if (expenseRecordDAO != null) {
            expenseRecordDAO.closeConnection();
        }
    }
}